package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.EmployeeService;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author fengzhu
 * @since 2024-10-10
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 实现单个查询和全部的查询,并且实现查询菜品的种类
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //初始化Page对象
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        //判读是否为空，添加查询条件
        queryWrapper.like(name !=null,Dish::getName,name);
        dishService.page(dishPage,queryWrapper);

        //对象拷贝，先拷贝的是page里面的信息
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> dishList =dishPage.getRecords();
        List<DishDto> list=   dishList.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();

            Category category = categoryService.getById(categoryId);
            //防止空指针异常
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
             return dishDto;
        }).toList();
        dishDtoPage.setRecords(list);
       return R.success(dishDtoPage);

    }

    /**
     *实现批量启售，停售 用来接受前端发来的status,并且更新到数据库中
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("status/{status}")
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids){
        dishService.UpdateByStatusByIds(status,ids);
        return R.success("成功");
    }

    /**
     * 实现删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("{}",ids);
        dishService.removeByIds(ids);
        return R.success("操作成功");
    }

    /**
     * 新建菜品，实现保存
     * @param request
     * @param dish
     * @return
     */
    @PostMapping
    public R<String>  save(HttpServletRequest request, @RequestBody Dish dish){
        Long id = (Long) request.getSession().getAttribute("employee");
        dish.setCreateUser(id);
        dish.setUpdateUser(id);
        dishService.save(dish);
        return R.success("成功");
    }

    /**
     * 根据id查询信息和口味信息，数据的回写
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDishByID(@PathVariable Long id){
        //两个表查询
        DishDto dishDto =    dishService.getByIdWithFlavor(id);
       return R.success(dishDto);
    }

    /**
     * 实现了菜品的修改保存
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDish(HttpServletRequest request,@RequestBody DishDto dishDto){
        Long empid =(Long) request.getSession().getAttribute("employee");
        dishDto.setUpdateUser(empid);
        dishDto.setCreateUser(empid);
        dishService.updateWithFlavor(dishDto,empid);
        return R.success("修改成功");
    }

    /**
     *在添加菜品页面映射出来菜品的信息，根据名子查询
     * @param categoryId
     * @param name
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(@RequestParam(required =false) Long categoryId,@RequestParam(required = false) String name) {
        // 根据 categoryId 查询相关的菜品
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        if(categoryId != null){
            queryWrapper.eq(Dish::getCategoryId,categoryId);
        }

        if(StringUtils.isNotBlank(name)){
            queryWrapper.like(Dish::getName,name);
        }
        List<Dish> dishList = dishService.list(queryWrapper);

        // 转换成 DishDto 并返回
        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            // 查询分类名称并设置

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }
}
